import type { IMiddleware } from "koa-router";

import { ArticleLog } from "../model";
import { makeResponse, HttpStatusCode } from "../util/response";

// 获取所有文章
export const getArticleLogs: IMiddleware = async ctx => {
  // 1. 获取 query 参数
  const current = ctx.query.current as any as number;
  const limit = ctx.query.limit as any as number;

  // 1.1 获取前面拿到的 total
  const { total } = ctx.state;

  // 2. 连接数据库获取 articleLogs
  const skipCount = (current - 1) * limit;
  const query = ArticleLog.find({})
    .skip(skipCount)
    .limit(limit)
    .populate({ path: "create_by", select: "name" })
    .populate({ path: "article", select: "title" });

  const result = await query.exec();

  // 3. 返回所有 articleLogs 包括 total
  makeResponse(ctx, HttpStatusCode.Ok, { result, total });
};
